class MyLinkedList {
    int size;
    ListNode head; //虚拟头节点

    public MyLinkedList() {
        this.size = 0;
        this.head = new ListNode(0); //虚拟头节点赋值
    }

    public int get(int index) {
        if(index < 0 || index >= size) return -1;
        ListNode cur = head.next;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
       addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(size,val);
    }

    public void addAtIndex(int index, int val) {
        if(index > size) return;
        if(index < 0) {
            index = 0;
        }
        size++;

        ListNode cur = head;
        ListNode newNode = new ListNode(val);

        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        newNode.next = cur.next;
        cur.next = newNode;
    }

    public void deleteAtIndex(int index) {
        ListNode cur = head;

        if(index < 0 || index+1 > size ) return;
        size--;

        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
    }

//    public int len(){
//        MyLinkedList cur;
//        cur = this.next;
//        int len = 0;
//        while (cur != null){
//            len++;
//            cur = cur.next;
//        }
//        return len;
//    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */